package com.zyy.config;

import com.zyy.pojo.Configuration;
import com.zyy.pojo.MappedStatement;
import com.zyy.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author zyy
 * @date 2020/11/7 8:03 下午
 * @description
 */
public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectNodes = rootElement.selectNodes("//select");
        for (Element selectNode : selectNodes) {
            putMappedStatement(selectNode,namespace,SqlCommandType.SELECT);
        }

        List<Element> insertNodes = rootElement.selectNodes("//insert");
        for (Element insertNode : insertNodes) {
            putMappedStatement(insertNode,namespace,SqlCommandType.INSERT);
        }

        List<Element> updateNodes = rootElement.selectNodes("//update");
        for (Element updateNode : updateNodes) {
            putMappedStatement(updateNode,namespace,SqlCommandType.UPDATE);
        }

        List<Element> deleteNodes = rootElement.selectNodes("//delete");
        for (Element deleteNode : deleteNodes) {
            putMappedStatement(deleteNode,namespace,SqlCommandType.DELETE);
        }

    }

    /**
     * 封装MappedStatement并添加到configuration中
     */
    private void putMappedStatement(Element element,String namespace,SqlCommandType sqlCommandType){
        String id = element.attributeValue("id");
        String resultType = element.attributeValue("resultType");
        String paramterType = element.attributeValue("paramterType");
        String sql = element.getTextTrim();
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setId(id);
        mappedStatement.setResultType(resultType);
        mappedStatement.setParamterType(paramterType);
        mappedStatement.setSql(sql);
        mappedStatement.setSqlCommandType(sqlCommandType);
        String key = namespace+"."+id;
        configuration.getMappedStatementMap().put(key,mappedStatement);
    }
}
